﻿#include "mazeproject.h"
#include "Maze.h"
#include<qfile.h>
#include<qtextstream.h>
#include <qbrush.h>
#include <qcolor.h>
#include<qtextcodec.h>
using namespace std;
using namespace liandan;
MazeProject::MazeProject(QWidget *parent, Qt::WFlags flags)
	: QMainWindow(parent, flags)
{
	ui.setupUi(this);
	//this->showMaximized();
	this->ui.tabWidget->clear();
	this->setFixedSize(this->width(),this->height());
	QTextCodec::setCodecForTr(QTextCodec::codecForName("GBK"));
	//this->process=QProgressDialog(this);
	for(int i=1;i!=21;i++)
	{
		QVariant var=QVariant(i);
		this->ui.comboBox->addItem(var.toString(),var);
		this->ui.comboBox_2->addItem(var.toString(),var);
	}
	this->scene=new QGraphicsScene();
	//migongwidget=new QWidget(this);
	//this->migongwidget->setFixedHeight(this->height()-30);
	//this->migongwidget->setFixedWidth(this->width()-15);
	 view= new QGraphicsView(this->scene);
	 this->painter=new QPainter(this->view);
	//this->doc
	this->ui.tabWidget->addTab(((QWidget*)(view)),"Maze");
	
	//this->setCentralWidget(view);
	//this->setContentsMargins(10,30,300,30);
	// ofstream os;
 //   os.open("1.txt");
 //   int j=0;
 //   vector<cell>datas;
 //   CvCapture*  pCap;// = NULL;
 //   //if(argc==2 && argv[1])
	//string filename="D:\\交大相关\\科创\\录像3.avi";

	//pCap = cvCaptureFromFile(filename.c_str());
 //   if(pCap==NULL) 
 //   {
	//printf("Can't open %s file\n","D:\交大相关\科创\trackCar.avi");
	////return -1;
 //   }
 //   IplImage* img = 0;
 //   if(!cvGrabFrame(pCap))
 //   {              // capture a frame
	//printf("Could not grab a frame\n\7");
	//exit(0);
 //   }
 //   img=cvRetrieveFrame(pCap);
 //   IplImage* biimg = cvCreateImage(cvGetSize(img),img->depth,img->nChannels);
 //   int width=img->width;  
 //   int height=img->height;
 //   string path("D:\\交大相关\\科创\\录像3.avi");
 //   MazeToData(path,datas,50,0,width,height,16,16,0);
 //   for(vector<cell>::iterator it=datas.begin();it!=datas.end();it++,j++)
	////os<<j<<"  "<<it->right<<"   "<<it->left<<"  "<<it->bottom<<"    "<<it->up<<'\n';
 //   
 //   cvSaveImage("2.jpg", img);
 //   //cout<<img->nChannels<<"　　　"<<"    "<<width<<"    "<<height<<"    "<<" "<<row_no<<" "<<col_no<<" "<<start_x;
	//QVector<QVector<cell>>Maze=QVector<QVector<cell>>();
	//for(int i=0;i!=16;i++)
	//{
	//	QVector<cell> tmp=QVector<cell>();
	//	for(int j=0;j!=16;j++)
	//	{
	//		tmp.push_back(datas.at(i*16+j));
	//	}
	//	Maze.push_back(tmp);
	//}
	//this->DrawMaze(Maze);
 //   //system("pause");
 //   //return 0;
}
void MazeProject::on_buttonStart_clicked()
{
	this->scene->clear();

	 ofstream os,os1;
    os.open("1.txt");
	os1.open("path.txt");
    int j=0;
    vector<cell>datas;
    CvCapture*  pCap;// = NULL;
    //if(argc==2 && argv[1])
	string filename=(this->searchPath).toStdString();;

	pCap = cvCaptureFromFile(filename.c_str());
    if(pCap==NULL) 
    {
	printf("Can't open %s file\n","D:\交大相关\科创\trackCar.avi");
	//return -1;
    }
    IplImage* img = 0;
    if(!cvGrabFrame(pCap))
    {              // capture a frame
	printf("Could not grab a frame\n\7");
	exit(0);
    }
    img=cvRetrieveFrame(pCap);
    IplImage* biimg = cvCreateImage(cvGetSize(img),img->depth,img->nChannels);
    int width=img->width;  
    int height=img->height;
	string path=filename;
	QString s="我都没辙了";
	//this->ui.label_6->setText(QObject::tr("你好"));
	//this->ui.label_4
   // string path("D:\\交大相关\\科创\\录像3.avi");
	int col=this->ui.comboBox_2->currentIndex()+1;
	int row=this->ui.comboBox->currentIndex()+1;
	wangjincheng::MazeToData(path,datas,50,0,width,height,row,col,0);
    //for(vector<cell>::iterator it=datas.begin();it!=datas.end();it++,j++)
	//os<<j<<"  "<<it->right<<"   "<<it->left<<"  "<<it->bottom<<"    "<<it->up<<'\n';
    
    cvSaveImage("2.jpg", img);
    //cout<<img->nChannels<<"　　　"<<"    "<<width<<"    "<<height<<"    "<<" "<<row_no<<" "<<col_no<<" "<<start_x;
	QVector<QVector<cell>>Maze=QVector<QVector<cell>>();
	for(int i=0;i!=row;i++)
	{
		QVector<cell> tmp=QVector<cell>();
		for(int j=0;j!=col;j++)
		{
			tmp.push_back(datas.at(i*16+j));
		}
		Maze.push_back(tmp);
	}

	// 读入冲刺路径
	string filename_rush = (this->rushPath).toStdString();
	CvCapture * pCap_rush = cvCaptureFromFile(filename_rush.c_str());
	if(pCap_rush==NULL) 
    {
		printf("Can't open %s file\n",filename_rush);
		//return -1;
    }

	// 算总帧数，用来搞进度条
	tot_f=cvGetCaptureProperty(pCap,CV_CAP_PROP_FRAME_COUNT)+cvGetCaptureProperty(pCap_rush,CV_CAP_PROP_FRAME_COUNT);
	count=0;

	// 把迷宫中0和1颠倒一下，因为分开写不一致导致
	vector<liandan::Cell> mazedata_rev;
	for (int i=0;i<datas.size();i++){
		liandan::Cell tmp;
		tmp.up = 1-datas[i].up;
		tmp.bottom = 1-datas[i].bottom;
		tmp.left = 1-datas[i].left;
		tmp.right = 1-datas[i].right;
		mazedata_rev.push_back(tmp);
	}
	liandan::Maze my_maze(row, col, 15, 0, 8, 7, mazedata_rev);	//	需要加入输入起点终点

	// 建立探索路径
	int tmp=get_pos_track_from_video(pCap);
	this->get_cell_track_from_data(Maze,col,row,this->mypoints_x,this->mypoints_y,width*1.0/col,height*1.0/row);
	int k=0;
	for(vector<int>::iterator it=this->res_column.begin();it!=this->res_column.end();it++,k++)
		os1<<*it<<"\t"<<this->res_row[k]<<"\t"<<this->check_pre[k]<<"\t"<<this->check_post[k]<<endl;
	os1<<"================================================="<<endl;
	
	for (int i=0;i<res_row.size();i++){
		liandan::TrackNode tmp;
		tmp.cellRow = res_row[i];
		tmp.cellColumn = res_column[i];
		tmp.time = res_time[i];
		my_explore_tracknodes.push_back(tmp);
	}
	liandan::Track my_explore_track(my_explore_tracknodes,my_maze);

	// 建立冲刺路径
	tmp=get_pos_track_from_video(pCap_rush);
	this->get_cell_track_from_data(Maze,col,row,this->mypoints_x,this->mypoints_y,width*1.0/col,height*1.0/row);
	k=0;
	for(vector<int>::iterator it=this->res_column.begin();it!=this->res_column.end();it++,k++)
		os1<<*it<<"\t"<<this->res_row[k]<<"\t"<<this->check_pre[k]<<"\t"<<this->check_post[k]<<endl;
	os1<<"================================================="<<endl;
	
	for (int i=0;i<res_row.size();i++){
		liandan::TrackNode tmp;
		tmp.cellRow = res_row[i];
		tmp.cellColumn = res_column[i];
		tmp.time = res_time[i];
		my_rush_tracknodes.push_back(tmp);
	}
	liandan::Track my_rush_track(my_rush_tracknodes,my_maze);

	// 根据跟踪结果修改起点终点信息 不要紧吧
	my_maze.setEndpoint(my_rush_tracknodes[0].cellRow,my_rush_tracknodes[0].cellColumn,my_rush_tracknodes[my_rush_tracknodes.size()-1].cellRow,my_rush_tracknodes[my_rush_tracknodes.size()-1].cellColumn);
	my_rush_track.setEndpoint(my_rush_tracknodes[0].cellRow,my_rush_tracknodes[0].cellColumn,my_rush_tracknodes[my_rush_tracknodes.size()-1].cellRow,my_rush_tracknodes[my_rush_tracknodes.size()-1].cellColumn);
	my_explore_track.setEndpoint(my_rush_tracknodes[0].cellRow,my_rush_tracknodes[0].cellColumn,my_rush_tracknodes[my_rush_tracknodes.size()-1].cellRow,my_rush_tracknodes[my_rush_tracknodes.size()-1].cellColumn);

	// 分析开始
	double cornerRate= this->ui.doubleSpinBox->value();//  1.5;
	double idealTime=this->ui.doubleSpinBox_2->value();//  1;
	double UTurnRate =this->ui.doubleSpinBox_3->value();// 2;

	//QString resultshow="分析结果";
	bool mazeValid=my_maze.isLegal();
	os1<<endl<<"迷宫合法性："<<endl;
	//resultshow+="迷宫合法性：";
	if (mazeValid){
		os1<<"合法"<<endl;
		this->mazeleagal="Leagal";
		//resultshow+="合法";
	} else {
		os1<<"不合法"<<endl;
		this->mazeleagal="Unleagal";

	}
	bool trackValid=my_explore_track.isLegal();
	os1<<endl<<"探索路径合法性："<<endl;
	if (trackValid){
		os1<<"合法"<<endl;
		this->searchpathleagal="Leagal";
	} else {
		os1<<"不合法"<<endl;
		this->searchpathleagal="Unleagal";
	}
	double coverRate=my_explore_track.getCoverage();
	os1<<endl<<"迷宫覆盖率："<<endl;
	os1<<coverRate<<endl;
	this->mazecoverrate=coverRate;
	double heightRate=my_explore_track.drawMaze(my_maze).getTotalHeight(cornerRate)/my_maze.getTotalHeight(cornerRate);
	os1<<endl<<"探索迷宫与实际迷宫高度比：";
	os1<<heightRate<<endl;
	double proportion=my_explore_track.drawMaze(my_maze).getBestTrack(cornerRate).getEvaluatedTime(idealTime,cornerRate,UTurnRate)/my_maze.getBestTrack(cornerRate).getEvaluatedTime(idealTime,cornerRate,UTurnRate);
	os1<<endl<<"探索最短路径与实际最短路径高度比：";
	os1<<proportion<<endl;
	double repeatExploreRate=my_explore_track.getRepetationRate();
	os1<<endl<<"探索路径重复率：";
	os1<<repeatExploreRate<<endl;
	double varityOfAlternation=my_explore_track.getVarietyOfAlternation(my_maze);
	os1<<endl<<"对岔路选择的丰富程度：";
	os1<<varityOfAlternation<<endl;

	bool rush_trackValid=my_rush_track.isLegal();
	QString rushle;
	os1<<endl<<"冲刺路径合法性"<<endl;
	if (rush_trackValid){
		os1<<"合法"<<endl;
		rushle="Leagal";
	} else {
		os1<<"不合法"<<endl;
		rushle="Not";
	}
	double proportion_rush_h=my_maze.getBestTrack(cornerRate).getEvaluatedTime(idealTime,cornerRate,UTurnRate)/my_rush_track.getEvaluatedTime(idealTime,cornerRate,UTurnRate);
	os1<<endl<<"理论冲刺高度与实际冲刺高度比例：";
	os1<<proportion_rush_h<<endl;
	double proportion_rush_t=my_maze.getBestTrack(cornerRate).getEvaluatedTime(idealTime,cornerRate,UTurnRate)/my_rush_track.getTotalTime();
	os1<<endl<<"理论冲刺时间与实际冲刺时间比例：";
	os1<<proportion_rush_t<<endl;
	int circleLength=my_rush_track.getCircleLength();
	os1<<endl<<"环形路径长度：";
	os1<<circleLength<<endl;

	process.hide();
	os1.close();
	
    //return 0;
	this->ui.tableView->clearSpans();
	this->ui.tableView->setEditTriggers(QAbstractItemView::NoEditTriggers);
	 QStandardItemModel *model = new QStandardItemModel;
 model->setColumnCount(2);
 model->setHeaderData(0,Qt::Horizontal,tr("属性"));
 model->setHeaderData(1,Qt::Horizontal,tr("数据"));
 //model->setHeaderData(2,Qt::Horizontal,tr("Data"));
// model->setHeaderData(3,Qt::Horizontal,tr("Duration"));
 // QStandardItem* item1 = new QStandardItem(tr("1"));
 QStandardItem* item2 = new QStandardItem(tr("迷宫合法性"));
 QStandardItem* item3 = new QStandardItem(this->mazeleagal);
// QStandardItem* item4 = new QStandardItem(tr("3:48"));
 QList<QStandardItem*> item;
 item << item2 << item3;// << item4;
 model->appendRow(item);


   //QStandardItem* item11= new QStandardItem(tr("2"));
 QStandardItem* item21 = new QStandardItem(tr("探索路径合法性"));
 QStandardItem* item31 = new QStandardItem(this->searchpathleagal);
// QStandardItem* item4 = new QStandardItem(tr("3:48"));
// QList<QStandardItem*> item;
 item.clear();
 item << item21<< item31;// << item4;
 model->appendRow(item);

  QStandardItem* item22 = new QStandardItem(tr("迷宫覆盖率"));
//  QString::fromcoverRate
  QStandardItem* item32 = new QStandardItem(QString::number(coverRate,'g',6));
// QStandardItem* item4 = new QStandardItem(tr("3:48"));
// QList<QStandardItem*> item;
 item.clear();
 item << item22<< item32;// << item4;
 model->appendRow(item);


  QStandardItem* item23 = new QStandardItem(tr("探索迷宫与实际迷宫高度比"));
//  QString::fromcoverRate
  QStandardItem* item33 = new QStandardItem(QString::number(heightRate,'g',6));
// QStandardItem* item4 = new QStandardItem(tr("3:48"));
// QList<QStandardItem*> item;
 item.clear();
 item << item23<< item33;// << item4;
 model->appendRow(item);

  QStandardItem* item24 = new QStandardItem(tr("探索最短路径与实际最短路径高度比"));
//  QString::fromcoverRate
  QStandardItem* item34 = new QStandardItem(QString::number(proportion,'g',6));
// QStandardItem* item4 = new QStandardItem(tr("3:48"));
// QList<QStandardItem*> item;
 item.clear();
 item << item24<< item34;// << item4;


  QStandardItem* item25= new QStandardItem(tr("探索路径重复率"));
//  QString::fromcoverRate
  QStandardItem* item35 = new QStandardItem(QString::number(repeatExploreRate,'g',6));
// QStandardItem* item4 = new QStandardItem(tr("3:48"));
// QList<QStandardItem*> item;
 item.clear();
 item << item25<< item35;// << item4;


 QStandardItem* item26= new QStandardItem(tr("对岔路选择的丰富程度"));
//  QString::fromcoverRate
  QStandardItem* item36 = new QStandardItem(QString::number(varityOfAlternation,'g',6));
// QStandardItem* item4 = new QStandardItem(tr("3:48"));
// QList<QStandardItem*> item;
 item.clear();
 item << item26<< item36;// << item4;


 model->appendRow(item);


 QStandardItem* item27= new QStandardItem(tr("冲刺路径合法性"));
//  QString::fromcoverRate
  QStandardItem* item37 = new QStandardItem(rushle);
// QStandardItem* item4 = new QStandardItem(tr("3:48"));
// QList<QStandardItem*> item;
 item.clear();
 item << item27<< item37;// << item4;


 model->appendRow(item);


 QStandardItem* item28= new QStandardItem(tr("理论冲刺高度与实际冲刺高度比例"));
//  QString::fromcoverRate
 QStandardItem* item38 = new QStandardItem(QString::number(proportion_rush_h,'g',6));
// QStandardItem* item4 = new QStandardItem(tr("3:48"));
// QList<QStandardItem*> item;
 item.clear();
 item << item28<< item38;// << item4;


 model->appendRow(item);



  QStandardItem* item29= new QStandardItem(tr("理论冲刺时间与实际冲刺时间比例"));
//  QString::fromcoverRate
 QStandardItem* item39 = new QStandardItem(QString::number(proportion_rush_t,'g',6));
// QStandardItem* item4 = new QStandardItem(tr("3:48"));
// QList<QStandardItem*> item;
 item.clear();
 item << item29<< item39;// << item4;


 model->appendRow(item);



  QStandardItem* item210= new QStandardItem(tr("环形路径长度"));
//  QString::fromcoverRate
 QStandardItem* item310 = new QStandardItem(QString::number(circleLength,'g',6));
// QStandardItem* item4 = new QStandardItem(tr("3:48"));
// QList<QStandardItem*> item;
 item.clear();
 item << item210<< item310;// << item4;


 model->appendRow(item);



 
 this->ui.tableView->setModel(model);
 this->DrawMaze(Maze);
}
void MazeProject::on_buttonImportSearch_clicked()
{
	QString fileName = QFileDialog::getOpenFileName(this, tr("Import File"), "untitledFolder", tr("*.avi"));
	if(!fileName.isEmpty())
	{
		this->searchPath=fileName;
	}
}
void MazeProject::on_buttonImportRush_clicked()
{
	QString fileName = QFileDialog::getOpenFileName(this, tr("Import File"), "untitledFolder", tr("*.avi"));
	if(!fileName.isEmpty())
	{
		this->rushPath=fileName;
	}
}
void MazeProject::DrawMaze(QVector<QVector<cell>>Maze)
{
	//this->scene
	int xsize=Maze[0].size();
	int ysize=Maze.size();
	qreal startx=0;
	qreal starty=0;
	qreal celllength=35;
	QPen pen=QPen();
	pen.setWidth(3);
	for(int i=0;i!=ysize;i++)
	{
		for(int j=0;j!=xsize;j++)
		{
			QPointF position=QPointF(startx,starty);
			if(Maze[i][j].up==1)
			{
				QGraphicsItem* item1=new QGraphicsLineItem(0,0,celllength,0);
				((QGraphicsLineItem*)(item1))->setPen(pen);
				this->scene->addItem(item1);
				item1->setPos(position);
			}
			if(Maze[i][j].bottom==1)
			{
				QGraphicsItem* item1=new QGraphicsLineItem(0,celllength,celllength,celllength);
				((QGraphicsLineItem*)(item1))->setPen(pen);
				this->scene->addItem(item1);
				item1->setPos(position);
			}
			if(Maze[i][j].left==1)
			{
				QGraphicsItem* item1=new QGraphicsLineItem(0,0,0,celllength);
				((QGraphicsLineItem*)(item1))->setPen(pen);
				this->scene->addItem(item1);
				item1->setPos(position);
			}
			if(Maze[i][j].right==1)
			{
				QGraphicsItem* item1=new QGraphicsLineItem(celllength,0,celllength,celllength);
				((QGraphicsLineItem*)(item1))->setPen(pen);
				this->scene->addItem(item1);
				item1->setPos(position);
			}
			startx=startx+celllength;
		}
		startx=0;
		starty=starty+celllength;
	}

	//QPointF startpoint=QPointF(0.0,0.0);
	//QPointF endpoint=QPointF(0.0,0.0);
	//int length=this->res_column.size();
	//qreal endx=0;
	//qreal endy=0;
	//startx=this->res_column[0]*celllength+celllength/2.0;
	//starty=this->res_row[0]*celllength+celllength/2.0;
	//pen.setColor(QColor(255,0,0));
	//for(int i=1;i!=length;i++)
	//{
	//	int rowindex=this->res_row[i];
	//	int colindex=this->res_column[i];
	//	endx=colindex*celllength+celllength/2.0;
	//	endy=rowindex*celllength+celllength/2.0;
	//	QGraphicsItem* item1=new QGraphicsLineItem(startx,starty,endx,endy);
	//	this->scene->addItem(item1);
	//	((QGraphicsLineItem*)(item1))->setPen(pen);
	//	item1->setPos(0,0);
	//	startx=endx;
	//	starty=endy;
	//}

	//startx=0;
	//starty=0;
	//for(int i=0;i!=length;i++)
	//{
	//	int rowindex=this->res_row[i];
	//	int colindex=this->res_column[i];
	//	startx=colindex*celllength;
	//	starty=rowindex*celllength;
	//	QGraphicsRectItem* item1=new QGraphicsRectItem(startx,starty,celllength,celllength);
	//	
	//	QBrush b(QColor(0,0,0,60));
	//	//QBrush b=painter->brush();
	//	//QColor c=b.color();
	//	//c.setRed(0);
	//	/*c.setGreen(0);
	//	c.setBlue(0);
	//	c.setAlphaF(110);
	//	b.setColor(c);*/
	//	item1->setBrush(b);
	//	//item1->
	//	//painter->drawRect(QRectF(startx,starty,celllength,celllength));
	//	this->scene->addItem(item1);
	//	item1->setPos(0,0);
	//}

	int length=this->my_explore_tracknodes.size();
	qreal endx=0;
	qreal endy=0;
	startx=this->my_explore_tracknodes[0].cellColumn*celllength+celllength/2.0;
	starty=this->my_explore_tracknodes[0].cellRow*celllength+celllength/2.0;
	pen.setColor(QColor(0,0,255));
	for(int i=1;i!=length;i++)
	{
		int rowindex=this->my_explore_tracknodes[i].cellRow;
		int colindex=this->my_explore_tracknodes[i].cellColumn;
		endx=colindex*celllength+celllength/2.0;
		endy=rowindex*celllength+celllength/2.0;
		QGraphicsItem* item1=new QGraphicsLineItem(startx,starty,endx,endy);
		this->scene->addItem(item1);
		((QGraphicsLineItem*)(item1))->setPen(pen);
		item1->setPos(0,0);
		startx=endx;
		starty=endy;
	}


	length=this->my_rush_tracknodes.size();
	endx=0;
	endy=0;
	startx=this->my_rush_tracknodes[0].cellColumn*celllength+celllength/2.0;
	starty=this->my_rush_tracknodes[0].cellRow*celllength+celllength/2.0;
	pen.setColor(QColor(255,0,0));
	for(int i=1;i!=length;i++)
	{
		int rowindex=this->my_rush_tracknodes[i].cellRow;
		int colindex=this->my_rush_tracknodes[i].cellColumn;
		endx=colindex*celllength+celllength/2.0;
		endy=rowindex*celllength+celllength/2.0;
		QGraphicsItem* item1=new QGraphicsLineItem(startx,starty,endx,endy);
		this->scene->addItem(item1);
		((QGraphicsLineItem*)(item1))->setPen(pen);
		item1->setPos(0,0);
		startx=endx;
		starty=endy;
	}



	length=this->my_explore_tracknodes.size();
	startx=0;
	starty=0;
	for(int i=0;i!=length;i++)
	{
		int rowindex=this->my_explore_tracknodes[i].cellRow;
		int colindex=this->my_explore_tracknodes[i].cellColumn;
		startx=colindex*celllength;
		starty=rowindex*celllength;
		QGraphicsRectItem* item1=new QGraphicsRectItem(startx,starty,celllength,celllength);
		
		QBrush b(QColor(0,0,0,60));
		//QBrush b=painter->brush();
		//QColor c=b.color();
		//c.setRed(0);
		/*c.setGreen(0);
		c.setBlue(0);
		c.setAlphaF(110);
		b.setColor(c);*/
		item1->setBrush(b);
		//item1->
		//painter->drawRect(QRectF(startx,starty,celllength,celllength));
		this->scene->addItem(item1);
		item1->setPos(0,0);
	}



}
int MazeProject::RunBlobTrackingAuto( CvCapture* pCap, CvBlobTrackerAuto* pTracker){
    int                     OneFrameProcess = 0;
    int                     key;
    int                     FrameNum = 0;
	IplConvKernel*          elementD   = cvCreateStructuringElementEx(3,3,1,1,CV_SHAPE_ELLIPSE);

	mypoints_x.clear();
	mypoints_y.clear();
	my_times.clear();

	double fps=cvGetCaptureProperty(pCap,CV_CAP_PROP_FPS);

    /* Main loop: */
    for( FrameNum=0; pCap && (key=cvWaitKey(OneFrameProcess?0:1))!=27; FrameNum++) {
        /* Main loop: */
        IplImage*   pImg   = NULL;
        IplImage*   pMask  = NULL;

        if(key!=-1) {
            OneFrameProcess = 1;
            if(key=='r')OneFrameProcess = 0;
        }
        pImg = cvQueryFrame(pCap);
        if(pImg == NULL) break;
		cvErode(pImg,pImg,elementD,3);
        /* Process: */
        pTracker->Process(pImg, pMask);

		if(pTracker->GetBlobNum()>0) {
			CvBlob* pB = pTracker->GetBlob(0);
			CvPoint p = cvPointFrom32f(CV_BLOB_CENTER(pB));
			mypoints_x.push_back(p.x);
			mypoints_y.push_back(p.y);
			my_times.push_back(1/fps*FrameNum);
		}
		count++;
		process.setValue(count);
    }   /*  Main loop. */

	if(elementD)cvReleaseStructuringElement( &elementD );
    return 0;
}   /* RunBlobTrackingAuto */

int MazeProject::get_pos_track_from_video(CvCapture* pCap){
    /* Main function: */
//    CvCapture*                  pCap = NULL;
    CvBlobTrackerAutoParam1     param = {0};
    CvBlobTrackerAuto*          pTracker = NULL;

	//this->process.setParent(this);
	//process.setLabelText(tr("process"));
	this->process.show();
	process.setRange(0,(int)(tot_f));
	process.setModal(true);

    {
        /* Create autotracker module and its components: */
        param.FGTrainFrames = 0;

        /* Create FG Detection module: */
        param.pFG = cvCreateFGDetectorBase(CV_BG_MODEL_FGD,NULL);
        if(!param.pFG)
            puts("Can not create FGDetector module");
        param.pFG->SetNickName("FG_0");

        /* Create Blob Entrance Detection module: */
        param.pBD = cvCreateBlobDetectorCC();
        if(!param.pBD)
            puts("Can not create BlobDetector module");
        param.pBD->SetNickName("BD_CC");

        /* Create blob tracker module: */
        param.pBT = cvCreateBlobTrackerCCMSPF();
        if(!param.pBT)
            puts("Can not create BlobTracker module");
        param.pBT->SetNickName("CCMSPF");

        /* Create blob trajectory post processing module: */
        param.pBTPP = cvCreateModuleBlobTrackPostProcKalman();
        if(!param.pBTPP)
            puts("Can not create blob trajectory post processing module");
        param.pBTPP->SetNickName("Kalman");

        param.UsePPData = 1;    // ÕâÐÐ¸ÉÂïµÄ£¿

        /* Create blob trajectory analysis module: */
        param.pBTA = cvCreateModuleBlobTrackAnalysisHistPVS();
        if(!param.pBTA)
            puts("Can not create blob trajectory analysis module");
        param.pBTA->SetNickName("HistPVS");

        /* Create whole pipline: */
        pTracker = cvCreateBlobTrackerAuto1(&param);
        if(!pTracker)
            puts("Can not create BlobTrackerAuto");
    }

    /* Run pipeline: */
    RunBlobTrackingAuto( pCap, pTracker);

    /* Release modules: */
    {
        if(param.pBT)cvReleaseBlobTracker(&param.pBT);
        if(param.pBD)cvReleaseBlobDetector(&param.pBD);
        if(param.pBTGen)cvReleaseBlobTrackGen(&param.pBTGen);
        if(param.pBTA)cvReleaseBlobTrackAnalysis(&param.pBTA);
        if(param.pFG)cvReleaseFGDetector(&param.pFG);
        if(pTracker)cvReleaseBlobTrackerAuto(&pTracker);
    }

    if(pCap)
        cvReleaseCapture(&pCap);
    return 0;
}

bool MazeProject::check_jianrong(QVector<QVector<cell>> &mazedata,int now_row,int now_column,int check_row,int check_column){
	//判断从check能否走到now
	if (now_row == check_row && now_column == check_column+1){
		return (mazedata[check_row][check_column].right == 0);
	} else if (now_row == check_row && now_column == check_column-1){
		return (mazedata[check_row][check_column].left == 0);
	} else if (now_row == check_row+1 && now_column == check_column){
		return (mazedata[check_row][check_column].bottom == 0);
	} else if (now_row == check_row-1 && now_column == check_column){
		return (mazedata[check_row][check_column].up == 0);
	} else 
		return false;
}

bool MazeProject::get_cell_track_from_data(
		QVector<QVector<cell>> &mazedata, 
		int maze_max_column,
		int maze_max_row,
		vector<double> car_x,
		vector<double> car_y,
		double cell_sizex,
		double cell_sizey,
		double start_x,
		double start_y){
	/* mazedata: JinCheng read first frame and then know connection between cells
	 * maze_max_x: the width of the mazedata
	 * maze_max_y: the height of the mazedata
	 * car_x: the position_x of car at each frame
	 * car_y: the position_y of car at each frame
	 * cell_size: real height of each cell
	 * start_x: real maze position_x in video
	 * start_y: real maze position_y in video
	 */
			
	// 小车坐标数据不匹配 报错
	if (car_x.size()!=car_y.size()){
		return false;
	}

	res_column.clear();
	res_row.clear();

	// 计算小车实时位置
	for (int i=0;i<car_x.size();i++){
		res_column.push_back(floor((car_x[i]-start_x)/cell_sizex));
		res_row.push_back(floor((car_y[i]-start_y)/cell_sizey));
		res_time.push_back(my_times[i]);
	}

	// 排除因错误识别而造成的超过迷宫格小车坐标点
	int i=0;
	while (i<res_column.size()){
		if (res_column[i]<0 || res_column[i]>=maze_max_column || res_row[i]<0 || res_row[i]>=maze_max_row){
			res_column.erase(res_column.begin()+i);
			res_row.erase(res_row.begin()+i);
			res_time.erase(res_time.begin()+i);
		} else {
			i++;
		}
	}

	// 有效数据过少 报错
	if (res_column.size()<5){
		return false;
	}

	cout<<"1"<<endl;

	// 排除重复点
	i = 1;
	while (i<res_column.size()){
		if (res_column[i]==res_column[i-1] && res_row[i]==res_row[i-1]){
			// 在原格点 无需重复记录
			res_column.erase(res_column.begin()+i);
			res_row.erase(res_row.begin()+i);
			res_time.erase(res_time.begin()+i);

		} else
			i++;
	}

	cout<<"2"<<endl;

	//排除干扰点

	i=0;
	while (i<res_column.size()){
		//	计算前后有效点距离
		int j;
		for (j=i-1;j>=0;j--)
			if (check_jianrong(mazedata,res_row[j],res_column[j],res_row[i],res_column[i]))
				break;
		check_pre.push_back(i-j);
		for (j=i+1;j<res_column.size();j++)
			if (check_jianrong(mazedata,res_row[i],res_column[i],res_row[j],res_column[j]))
				break;
		check_post.push_back(j-i);
		i++;
	}
	i=0;
	while (i<res_column.size()){
		if (check_post[i]>=2){
			int j=i+1;
			while (j<res_column.size() && check_post[j]>=2)
				j++;
			if (check_pre[j] >= j-i+1 && check_pre[j] <= j-i+3){
				while (check_pre[j]>1){
					res_column.erase(res_column.begin()+j-1);
					res_row.erase(res_row.begin()+j-1);
					res_time.erase(res_time.begin()+j-1);
					check_pre.erase(check_pre.begin()+j-1);
					check_post.erase(check_post.begin()+j-1);
					j--;
					check_pre[j]--;
				}
			}else{
				cout<<"error too big"<<endl;
				i=j;
			}
		} else 
			i++;
	}

	cout<<"3"<<endl;

	i=0;
	while (i<res_column.size()){
		if (check_pre[i]>=2){
			int j=i+1;
			while (j<res_column.size() && check_pre[j]>=2)
				j++;
			if (j>=res_column.size()){
				if (j-i>5){
					cout<<"error too big"<<endl;
					break;
				} else {
					while (i<res_column.size()){
						res_column.erase(res_column.begin()+i);
						res_row.erase(res_row.begin()+i);
						res_time.erase(res_time.begin()+i);
						check_pre.erase(check_pre.begin()+i);
						check_post.erase(check_post.begin()+i);
					}
					check_post[i-1]=1;
				}
			} else if (check_post[i-1]>=j-i && check_post[i-1]<=j-i+2){
					for (int tmp_t=0;tmp_t<check_post[i-1]-1;tmp_t++){
						res_column.erase(res_column.begin()+i);
						res_row.erase(res_row.begin()+i);
						res_time.erase(res_time.begin()+i);
						check_pre.erase(check_pre.begin()+i);
						check_post.erase(check_post.begin()+i);
					}
					check_post[i-1]=1;
					check_pre[i]=1;
				}else{
					cout<<"error too big"<<endl;
					i++;
				}
		} else 
			i++;
	}

	cout<<"4"<<endl;

	bool right=true;
	i=0;
	while (i<res_column.size()){
		if (check_post[i]>1 && check_pre[i]<2 && check_post[i+1]<2 && check_pre[i+1]>1){
			int gai_column,gai_row;
			gai_column = (res_column[i-1]+res_column[i+1])/2;
			gai_row = (res_row[i-1]+res_row[i+1])/2;
			if (check_jianrong(mazedata,res_row[i-1],res_column[i-1],gai_row,gai_column) &&
					check_jianrong(mazedata,gai_row,gai_column,res_row[i+1],res_column[i+1])){
				res_column[i]=gai_column;
				res_row[i]=gai_row;
				res_time[i]=(res_time[i-1]+res_time[i+1])/2;
				check_post[i]=1;
				check_pre[i+1]=1;
				i++;
				continue;
			}
			gai_column = (res_column[i]+res_column[i+2])/2;
			gai_row = (res_row[i]+res_row[i+2])/2;
			if (check_jianrong(mazedata,res_row[i],res_column[i],gai_row,gai_column) &&
					check_jianrong(mazedata,gai_row,gai_column,res_row[i+2],res_column[i+2])){
				res_column[i+1]=gai_column;
				res_row[i+1]=gai_row;
				res_time[i]=(res_time[i]+res_time[i+2])/2;
				check_post[i]=1;
				check_pre[i+1]=1;
				i++;
				continue;
			} else {
				cout<<"error too big"<<endl;
				right=false;
				i++;
			}
		} else 
			i++;
	}

	cout<<"5"<<endl;

	return right;
}



MazeProject::~MazeProject()
{

}
